package com.tuananh.radnom.persist.imp.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;

import com.tuananh.radnom.model.AbstractConfiguration;
import com.tuananh.radnom.persist.AbstractPersitor;
import com.tuananh.radnom.persist.ConfigLoader;
import com.tuananh.radnom.persist.Rollbackable;

public abstract class XmlDAO extends AbstractPersitor {
	String configPath;
	public static Marshaller marshaller;
	static Unmarshaller unmarshaller;
	static ConfigLoader loader;

	AbstractConfiguration configuration;
	AbstractConfiguration savedConfiguration;

	public ConfigLoader getLoader() {
		return loader;
	}

	public void setLoader(ConfigLoader loader) {
		XmlDAO.loader = loader;
	}

	public XmlDAO() {

	}

	public XmlDAO(String path) {
		File file = new File(path);
		configPath = path;
	}

	public AbstractConfiguration getConfiguration() {
		return configuration;
	}

	public void setConfiguration(AbstractConfiguration configuration) {
		this.configuration = configuration;
	}

	public AbstractConfiguration getSavedConfiguration() {
		return savedConfiguration;
	}

	public void setSavedConfiguration(AbstractConfiguration savedConfiguration) {
		this.savedConfiguration = savedConfiguration;
	}

	public boolean rollback() {
		// TODO Auto-generated method stub
		configuration = savedConfiguration.clone();
		try {
			loader.getMarshaller().marshal(configuration,
					new StreamResult(new FileOutputStream(configuration.getConfigPath())));
		} catch (XmlMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}
	public boolean commit() {
		// TODO Auto-generated method stub
		try {
			loader.getMarshaller().marshal(configuration,
					new StreamResult(new FileOutputStream(configuration.getConfigPath())));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		savedConfiguration = configuration.clone();
		return true;
	}
}
